<template>
  <div class="mod-prod">
    <avue-crud
      ref="crud"
      :page="page"
      :data="dataList"
      :option="tableOption"
      :permission="permission"
      :table-loading="dataListLoading"
      @search-change="searchChange"
      @selection-change="selectionChange"
      @on-load="getDataList"
      @row-del="handleDelete"
    >
      <template #menu-left>
        <el-button
          v-if="isAuth('social:posts:save')"
          type="primary"
          icon="Plus"
          @click="addOrUpdateHandle()"
        >
          新增
        </el-button>
        <el-button
          v-if="isAuth('social:posts:delete') && dataListSelections.length > 0"
          type="danger"
          icon="Delete"
          @click="handleDelete()"
        >
          批量删除
        </el-button>
        <el-button
          v-if="isAuth('social:post:audit') && dataListSelections.length > 0"
          type="success"
          icon="Check"
          @click="handleBatchAudit('approved')"
        >
          批量通过
        </el-button>
        <el-button
          v-if="isAuth('social:post:audit') && dataListSelections.length > 0"
          type="danger"
          icon="Close"
          @click="handleBatchAudit('rejected')"
        >
          批量拒绝
        </el-button>
      </template>

      <!-- 媒体内容插槽 -->
      <template #mediaContent="scope">
        <el-image
          v-if="scope.row.type === 'image'"
          :src="scope.row.mediaUrl"
          style="width: 100px; height: 100px"
          :preview-src-list="[scope.row.mediaUrl]"
        />
        <video
          v-else-if="scope.row.type === 'video'"
          :src="scope.row.mediaUrl"
          controls
          style="width: 200px; height: 100px"
        />
      </template>

      <!-- 类型插槽 -->
      <template #type="scope">
        <el-tag :type="typeStyle[scope.row.type]?.type">
          {{ typeStyle[scope.row.type]?.label }}
        </el-tag>
      </template>

      <!-- 状态插槽 -->
      <template #status="scope">
        <el-tag :type="STATUS_CONFIG[scope.row.status]?.type">
          {{ STATUS_CONFIG[scope.row.status]?.label }}
        </el-tag>
      </template>

      <!-- 操作列插槽 -->
      <template #menu="scope">
        <el-button
          type="primary"
          link
          v-if="isAuth('social:posts:update')"
          @click="addOrUpdateHandle(scope.row.postId)"
        >
          编辑
        </el-button>
        <el-button
          v-if="scope.row.status === 'pending'"
          type="success"
          link
          @click="handleAudit(scope.row, 'approved')"
        >
          通过
        </el-button>
        <el-button
          v-if="scope.row.status === 'pending'"
          type="danger"
          link
          @click="handleAudit(scope.row, 'rejected')"
        >
          拒绝
        </el-button>
        <el-button
          type="danger"
          link
          v-if="isAuth('social:posts:delete')"
          @click="handleDelete(scope.row)"
        >
          删除
        </el-button>
      </template>
    </avue-crud>

    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refresh-data-list="getDataList"
      @close="addOrUpdateVisible = false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils'
import http from '@/utils/http'
import AddOrUpdate from './add-or-update.vue'

// 类型样式配置
const typeStyle = {
  'text': { label: '文本', type: '' },
  'image': { label: '图片', type: 'success' },
  'video': { label: '视频', type: 'warning' }
}

// 状态配置
const STATUS_CONFIG = {
  'pending': { label: '待审核', type: 'info' },
  'approved': { label: '已通过', type: 'success' },
  'rejected': { label: '未通过', type: 'danger' }
}

// 添加状态映射
const STATUS_MAP = {
  '待审核': 'pending',
  '已通过': 'approved',
  '未通过': 'rejected'
}

// 表格配置
const tableOption = reactive({
  addBtn: false,
  delBtn: true,
  menuWidth: 280,
  selection: true,
  index: true,
  indexLabel: '序号',
  indexWidth: 60,
  menuAlign: 'center',
  align: 'center',
  column: [
    {
      label: '发帖人',
      prop: 'nickName',
      search: true
    },
    {
      label: '内容',
      prop: 'content',
      minWidth: 200,
      showOverflowTooltip: true,
      overHidden: true
    },
    {
      label: '媒体链接',
      prop: 'mediaUrl',
      slot: true,
      minWidth: 150,
      overHidden: true
    },
    {
      label: '类型',
      prop: 'type',
      slot: true
    },
    {
      label: '状态',
      prop: 'status',
      slot: true,
      search: true,
      type: 'select',
      dicData: [
        { label: '待审核', value: 'pending' },
        { label: '已通过', value: 'approved' },
        { label: '未通过', value: 'rejected' }
      ]
    }
  ]
})

// 权限配置
const permission = reactive({
  addBtn: isAuth('social:posts:save'),
  delBtn: true,
  editBtn: false
})

// 分页配置
const page = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

const dataList = ref([])
const dataListLoading = ref(false)
const dataListSelections = ref([])
const addOrUpdateVisible = ref(false)

const crud = ref(null)
const addOrUpdate = ref(null)

onMounted(() => {
  console.log('审核权限:', isAuth('social:post:audit'))
})

const getDataList = (pageParam, params, done) => {
  dataListLoading.value = true
  http({
    url: http.adornUrl('/social/post/page'),
    method: 'get',
    params: http.adornParams({
      current: pageParam?.currentPage || page.currentPage,
      size: pageParam?.pageSize || page.pageSize
    })
  }).then(({ data }) => {
    console.log('获取到的数据:', data.records)
    // 打印每条数据的状态
    data.records.forEach(item => {
      console.log(`帖子ID: ${item.postId}, 状态: ${item.status}`)
    })
    dataList.value = data.records
    page.total = data.total
    dataListLoading.value = false
    done?.()
  })
}

const searchChange = (params, done) => {
  getDataList(page, params, done)
}

const selectionChange = (val) => {
  dataListSelections.value = val
}

const addOrUpdateHandle = (postId) => {
  addOrUpdateVisible.value = true
  nextTick(async () => {
    try {
      if (addOrUpdate.value) {
        await addOrUpdate.value.init(postId)
      } else {
        ElMessage.error('组件初始化失败')
        addOrUpdateVisible.value = false
      }
    } catch (error) {
      console.error('初始化失败:', error)
      ElMessage.error('初始化失败')
      addOrUpdateVisible.value = false
    }
  })
}

const deleteHandle = (postId) => {
  if (postId === undefined || postId === null) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm(
    '确定要删除该帖子吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    http({
      url: http.adornUrl(`/social/post/${postId}`),
      method: 'delete'
    }).then((res) => {
      if (res && res.code === '00000') {
        ElMessage.success('删除成功')
        getDataList()
      } else {
        ElMessage.error(res?.msg || '删除失败')
      }
    }).catch(() => {
      ElMessage.error('删除失败')
    })
  })
}

const handleDelete = (row, index) => {
  let ids = []
  if (row && row.postId) {
    // 单个删除
    ids = [row.postId]
  } else {
    // 批量删除
    ids = dataListSelections.value.map(item => item.postId)
  }
  
  if (ids.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的${ids.length}条数据吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    http({
      url: http.adornUrl('/social/post/delete'),
      method: 'post',
      data: ids
    }).then((res) => {
      if (res && res.code === '00000') {
        ElMessage.success('删除成功')
        getDataList()
      } else {
        ElMessage.error(res?.msg || '删除失败')
      }
    }).catch(() => {
      ElMessage.error('删除失败')
    })
  })
}

// 单个审核
const handleAudit = (row, action) => {
  if (!row || !row.postId) {
    ElMessage.warning('请选择要审核的数据')
    return
  }

  const statusText = action === 'approved' ? '通过' : '拒绝'
  
  ElMessageBox.prompt(
    `请输入${statusText}理由（可选）：`,
    '审核确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: action === 'approved' ? 'success' : 'warning',
      inputPattern: /^[\s\S]*$/,
      inputValidator: (value) => {
        return true // 允许空值
      }
    }
  ).then(({ value: reason }) => {
    http({
      url: http.adornUrl(`/social/post/audit/${row.postId}`),
      method: 'put',
      params: {
        action: action,
        reason: reason || ''
      }
    }).then((res) => {
      if (res.code === '00000') {
        ElMessage.success(`${statusText}成功`)
        getDataList()
      } else {
        ElMessage.error(res.msg || `${statusText}失败`)
      }
    }).catch((error) => {
      console.error('审核失败:', error)
      ElMessage.error(`${statusText}失败`)
    })
  }).catch(() => {})
}

// 批量审核
const handleBatchAudit = (action) => {
  const ids = dataListSelections.value.map(item => item.postId)
  
  if (ids.length === 0) {
    ElMessage.warning('请选择要审核的数据')
    return
  }

  const statusText = action === 'approved' ? '通过' : '拒绝'
  
  ElMessageBox.prompt(
    `请输入批量${statusText}理由（可选）：`,
    '批量审核确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: action === 'approved' ? 'success' : 'warning',
      inputPattern: /^[\s\S]*$/,
      inputValidator: (value) => {
        return true
      }
    }
  ).then(({ value: reason }) => {
    // 使用 Promise.all 处理批量请求
    const promises = ids.map(id => 
      http({
        url: http.adornUrl(`/social/post/audit/${id}`),
        method: 'put',
        params: {
          action: action,
          reason: reason || ''
        }
      })
    )

    Promise.all(promises)
      .then(() => {
        ElMessage.success(`批量${statusText}成功`)
        getDataList()
      })
      .catch((error) => {
        ElMessage.error(`批量${statusText}失败：${error.message}`)
      })
  }).catch(() => {})
}
</script>

<style scoped>
.mod-prod {
  .el-button {
    margin-right: 8px;
    padding: 4px 8px;
  }
  
  .el-button + .el-button {
    margin-left: 0;
  }

  .el-button--link {
    height: auto;
    min-height: 28px;
  }
}
</style>

